package top.huhuiyu.springboot.study.interceptor;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import top.huhuiyu.springboot.study.util.IpUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Map;

/**
 * @author 胡辉煜
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AppInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    log.debug("拦截器前置处理");
    // 获取客户端ip地址
    String ip = IpUtils.getIpAddr(request);
    log.debug("客户端ip地址：{}", ip);
    // 获取请求的url地址
    String url = request.getRequestURI();
    log.debug("请求的url地址：{}", url);
    // 获取请求的参数信息
    Map<String, String[]> parmas = request.getParameterMap();
    parmas.forEach((k, v) -> {
      log.debug("请求参数：{}={}", k, Arrays.toString(v));
    });
    // 如果是控制器，获取控制器相关信息
    if (handler instanceof HandlerMethod) {
      HandlerMethod hm = (HandlerMethod) handler;
      log.debug("调用的是控制器");
      Class<?> clazz = hm.getBeanType();
      log.debug("控制器的类型：{}", clazz.getName());
      log.debug("控制器的方法：{}", hm.getMethod().getName());
    }
    return true;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    log.debug("拦截器尾置处理");
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    log.debug("拦截器完成");
  }
}
